<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/2/25
 * Time: 18:16
 */

namespace app\admin\controller;


use pay\Ali;
use pay\Wxservicer;
use think\Db;
use think\Request;

class Orderg extends Base
{
    /**
     * 礼包订单首页
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $bog_status = input('bog_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');
            $bog_aftersale_status = input('bog_aftersale_status');
            $bog_pay_type = input('bog_pay_type');
            $bog_dui = input('bog_dui');
        
            $where = [];
            if(isset($keyword) && $keyword != ''){
                $where['bog_id|bog_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['a1.user_real_name|a1.user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($bog_status) && $bog_status != ''){
                if($bog_status != -1){
                    $where['bog_status'] = $bog_status;
                }
            }else{
                $where['bog_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['bog_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['bog_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['bog_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['bog_create_time'] = ['<=', $end_time];
            }
            if(isset($bog_aftersale_status) && $bog_aftersale_status != ''){
                $where['bog_aftersale_status'] = $bog_aftersale_status;
            }
            if(isset($bog_pay_type) && $bog_pay_type != ''){
                $where['bog_pay_type'] = $bog_pay_type;
            }
            if(isset($bog_dui) && $bog_dui != ''){
                $where['bog_dui'] = $bog_dui;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
        
            $count = Db::table('up_bo_orderg')
                ->join('up_u_user a1', 'bog_user_id = a1.user_id', 'LEFT')
                ->join('up_u_user a2', 'bog_up_user_id = a2.user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = bog_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
                ->where($where)
                ->count('bog_id');
            $lists = Db::table('up_bo_orderg')
                ->join('up_u_user a1', 'bog_user_id = a1.user_id', 'LEFT')
                ->join('up_u_user a2', 'bog_up_user_id = a2.user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = bog_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
                ->field('bog_id, bog_number, bog_is_pay, bog_total_price, bog_remark, bog_status, 
                bog_create_time, bog_express_company, bog_express_code, a1.user_real_name, a1.user_phone, 
                bog_addr_id, concat(u1.district,"",u2.district, "", u3.district, "", addr_address) address, 
                addr_user_name, addr_user_phone, a1.user_shop_name, bog_cancel_reason, gift_name, bog_indate, 
                bog_indate_month, bog_aftersale_status, bog_get_way, bog_pay_type, a2.user_real_name up_name, 
                a2.user_giftbag_level, bog_up_user_id, bog_dui, bog_dui_admin')
                ->where($where)
                ->order('bog_create_time desc')
                ->page($Nowpage,$limits)
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 取消订单
     * @return mixed|\think\response\Json
     */
    public function orderCancel(){
        $bog_id = input('bog_id');
        if(Request::instance()->isPost()){
            $reason = trim(input('reason'));
            $order = Db::table('up_bo_orderg')
                ->where('bog_id', $bog_id)
                ->field('bog_user_id, bog_status, bog_total_price, bog_gift_id, bog_pay_type, bog_number')
                ->find();
            
            if($order['bog_status'] != 1) return json(['code' => 100, 'msg' => '订单状态异常，请刷新列表页重试']);
            
            $update = [
                'bog_id' => $bog_id,
                'bog_status' => 6,
                'bog_cancel_reason' => $reason,
                'bog_cancel_time' => date('Y-m-d H:i:s')
            ];

            // 修改订单状态
            $res = Db::table('up_bo_orderg')->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        return $this->fetch('', ['bog_id' => $bog_id]);
    }
    
    /**
     * 发货
     * @return mixed|\think\response\Json
     */
    public function orderSend(){
        $bog_id = input('bog_id');
        if(Request::instance()->isPost()){
            $bog_express_company = trim(input('bog_express_company'));
            $bog_express_code = trim(input('bog_express_code'));
            
            $order_status = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->value('bog_status');
            if($order_status != 2) return json(['code' => 100, 'msg' => '订单状态异常，请刷新列表页重试']);
            
            $res = Db::table('up_bo_orderg')
                ->update([
                    'bog_id' => $bog_id,
                    'bog_status' => 3,
                    'bog_send_time' => date('Y-m-d H:i:s'),
                    'bog_express_company' => $bog_express_company,
                    'bog_express_code' => $bog_express_code
                ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $wuliu = Db::table('up_about')->where('id', 7)->value('content');
        return $this->fetch('', ['bog_id' => $bog_id, 'wuliu' => $wuliu]);
    }
    
    /**
     * 编辑物流
     * @return mixed|\think\response\Json
     */
    public function updateWuLiu(){
        $bog_id = input('bog_id');
        if(Request::instance()->isPost()){
            $bog_express_company = trim(input('bog_express_company'));
            $bog_express_code = trim(input('bog_express_code'));
            
            $res = Db::table('up_bo_orderg')
                ->update([
                    'bog_id' => $bog_id,
                    'bog_express_company' => $bog_express_company,
                    'bog_express_code' => $bog_express_code
                ]);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $wuliu = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->field('bog_express_company, bog_express_code')->find();
        return $this->fetch('', ['bog_id' => $bog_id, 'wuliu' => $wuliu]);
    }
    
    /**
     * 确认收货
     * @return \think\response\Json
     */
    public function orderAffirm(){
        $bog_id = input('id');
        
        $order = Db::table('up_bo_orderg')->where('bog_id', $bog_id)->field('bog_user_id, bog_status, bog_gift_id, bog_total_price')->find();
        if($order['bog_status'] != 3) return json(['code' => 100, 'msg' => '订单状态异常']);

        // 修改订单状态
        $res = Db::table('up_bo_orderg')->update([
            'bog_id' => $bog_id,
            'bog_status' => 4,
            'bog_over_time' => date('Y-m-d H:i:s'),
            'bog_get_way' => '后台确认收货'
        ]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 审核售后
     * @return mixed|\think\response\Json
     */
    public function checkAftersale(){
        $bog_id = input('bog_id');
        if(Request::instance()->isPost()){
            $refuse_reason = input('refuse_reason');
            $bog_aftersale_status = input('bog_aftersale_status'); // 3 通过  4 拒绝
            if($bog_aftersale_status == 4 && !$refuse_reason) return json(['code' => 100, 'msg' => '请输入拒绝原因']);

            $time = date('Y-m-d H:i:s');
            $update['bog_check_time'] = $time;
            $update['bog_id'] = $bog_id;
            if($bog_aftersale_status == 3){
                $update['bog_aftersale_status'] = 3;
            }else{
                $update['bog_aftersale_status'] = 4;
                $update['bog_aftersale_refuse_reason'] = $refuse_reason;
            }
            $res = Db::table('up_bo_orderg')->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $aftersale = Db::table('up_bo_orderg')->where('bog_id', $bog_id)
            ->field('bog_aftersale_reason, bog_aftersale_time')->find();
        return $this->fetch('', ['bog_id' => $bog_id, 'aftersale' => $aftersale]);
    }

    /**
     * 延长有效期
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function orderIndate(){
        $bog_id = input('bog_id');
        $order = Db::table('up_bo_orderg')
            ->where('bog_id', $bog_id)
            ->field('bog_indate, bog_indate_month, bog_zeng_number')
            ->find();
        if(Request::instance()->isPost()){
            $edit_type = input('edit_type');
            $number = input('number');
            if(!$edit_type) return json(['code' => 100, 'msg' => '请选择操作方式']);
            if($edit_type == 1){
                $bog_indate = date('Y-m', strtotime("last day of +{$number} month", strtotime($order['bog_indate'])));
                $update = [
                    'bog_indate' => $bog_indate,
                    'bog_indate_month' => $order['bog_indate_month'] + $number,
                    'bog_zeng_number' => $order['bog_zeng_number'] + $number
                ];
                $desc = '后台手动增加';
                $m_number = $number;
            }else{
                $update = [
                    'bog_zeng_number' => $order['bog_zeng_number'] - $number
                ];
                $desc = '后台手动减少';
                $m_number = 0;
            }
            Db::startTrans();
            try{
                // 更新订单
                Db::table('up_bo_orderg')->where('bog_id', $bog_id)->update($update);

                // 日志
                insertGiftbagLog($bog_id, $desc, $m_number, $number);

                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('', ['bog_id' => $bog_id, 'order' => $order]);
    }

    /**
     * 已对账
     * @return \think\response\Json
     */
    public function orderDui(){
        $bog_id = input('id');
        $res = Db::table('up_bo_orderg')
            ->where('bog_id', $bog_id)
            ->update(['bog_dui' => 2, 'bog_dui_admin' => session('username')]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $order_ids = input('ids');

        $where = [];
        if($order_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $bog_status = input('bog_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');
            $bog_aftersale_status = input('bog_aftersale_status');
            $bog_pay_type = input('bog_pay_type');
            $bog_dui = input('bog_dui');

            if(isset($keyword) && $keyword != ''){
                $where['bog_id|bog_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['a1.user_real_name|a1.user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($bog_status) && $bog_status != ''){
                if($bog_status != -1){
                    $where['bog_status'] = $bog_status;
                }
            }else{
                $where['bog_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['bog_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['bog_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['bog_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['bog_create_time'] = ['<=', $end_time];
            }
            if(isset($bog_aftersale_status) && $bog_aftersale_status != ''){
                $where['bog_aftersale_status'] = $bog_aftersale_status;
            }
            if(isset($bog_pay_type) && $bog_pay_type != ''){
                $where['bog_pay_type'] = $bog_pay_type;
            }
            if(isset($bog_dui) && $bog_dui != ''){
                $where['bog_dui'] = $bog_dui;
            }
        }else{
            if($order_ids == ''){
                return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            }
            $where['bog_id'] = ['IN', $order_ids];
        }

        $lists = Db::table('up_bo_orderg')
            ->join('up_u_user', 'bog_user_id = user_id', 'LEFT')
            ->join('up_user_address', 'addr_id = bog_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->join('up_bo_giftbag', 'bog_gift_id = gift_id', 'LEFT')
            ->field('bog_number, bog_is_pay, bog_total_price, bog_remark, bog_status, bog_create_time, 
            bog_express_company, bog_express_code, user_real_name, user_phone, bog_pay_time, 
            bog_send_time, bog_over_time, bog_close_time, bog_cancel_time, addr_user_name, addr_user_phone, 
            concat(u1.district,"",u2.district, "", u3.district, "", addr_address) address, 
            user_shop_name, gift_name, bog_indate, bog_indate_month, bog_cancel_reason, bog_id')
            ->where($where)
            ->order('bog_create_time desc')
            ->select();
        foreach($lists as $k => $v){
            // 物流单号
            $lists[$k]['bog_express_code'] = "\t". $v['bog_express_code'] ."\t";
            // 下单人手机号
            $lists[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 订单号
//            $lists[$k]['bo_number'] = "\t" . $v['order_number'] . "\t";
            // 总金额
            $lists[$k]['bog_total_price'] = "\t" . $v['bog_total_price'] . "\t";
            // 支付状态
            $lists[$k]['bog_is_pay'] = $v['bog_is_pay'] == 1 ? '未支付' : '已支付';
            // 订单状态
            switch($v['bog_status']){
                case 1:
                    $lists[$k]['bog_status'] = '待付款';
                    break;
                case 2:
                    $lists[$k]['bog_status'] = '待发货';
                    break;
                case 3:
                    $lists[$k]['bog_status'] = '待收货';
                    break;
                case 4:
                    $lists[$k]['bog_status'] = '已完成';
                    break;
                case 5:
                    $lists[$k]['bog_status'] = '已关闭';
                    break;
                case 6:
                    $lists[$k]['bog_status'] = '已取消';
                    break;
                default:
                    $lists[$k]['bog_status'] = '未知';
            }
            
        }
        $cellname = [
            ['bog_id', '订单ID', 10, 'LEFT'],
            ['bog_number', '订单编号', 20, 'LEFT'],
            ['gift_name', '礼包', 30, 'LEFT'],
            ['bog_is_pay', '支付状态', 15, 'LEFT'],
            ['bog_total_price', '订单总金额', 15, 'LEFT'],
            ['bog_status', '订单状态', 15, 'LEFT'],
            ['user_real_name', '下单用户', 15, 'LEFT'],
            ['user_phone', '下单手机号', 15, 'LEFT'],
            ['bog_remark', '备注', 20, 'LEFT'],
            ['address', '收获地址', 30, 'LEFT'],
            ['addr_user_name', '收货人', 15, 'LEFT'],
            ['addr_user_phone', '收货人手机号', 15, 'LEFT'],
            ['bog_indate', '有效期', 15, 'LEFT'],
            ['bog_indate_month', '剩余月数', 15, 'LEFT'],
            ['user_shop_name', '店铺名称', 15, 'LEFT'],
            ['bog_express_company', '快递公司', 15, 'LEFT'],
            ['bog_express_code', '快递单号', 20, 'LEFT'],
            ['bog_create_time', '下单时间', 20, 'LEFT'],
            ['bog_pay_time', '付款时间', 20, 'LEFT'],
            ['bog_send_time', '发货时间', 20, 'LEFT'],
            ['bog_over_time', '收货时间', 20, 'LEFT'],
            ['bog_close_time', '关闭时间', 20, 'LEFT'],
            ['bog_cancel_time', '取消时间', 20, 'LEFT'],
            ['bog_cancel_reason', '取消原因', 20, 'LEFT']
        ];
        $res = exportExcelZhy('礼包订单', 'Gift_order', $cellname, $lists);
        return json($res);
    }
}